/**
 * desc: 公用的下拉搜索框
 * @ onChange: {func} 选择项发生变化时的事件
 * @ index: {number} 如果是在表格中，把下标返回
 * @ value: {object} 对象，包含storeID和storeName, 如：{ storeId: 1, storeName: '听雨轩', ... }
 */

 import React from 'react';
 import { queryFactoryList } from '@/services/common';
 import { setStoreList, getStoreList } from '@/utils/authority';
 import { customTrimFunc } from '@/utils/utils.jsx';
 import { Popover, Input, Tooltip, Select } from 'antd';
 import { pull, find, slice, union } from 'lodash';
 import { CloseOutlined } from '@ant-design/icons';
 import styles from './index.module.less';
 
 const { Option } = Select;
 export default class FuzzyQueryStore extends React.PureComponent {
 
   constructor(props){
     super(props);
     this.state  = {
       data: props?.data || [],
       visible: 1,
       loading: false,
       storeId: props.value,
       inputVal: props.storeName,
       storeArr: getStoreList() ? JSON.parse(getStoreList()) :  [],
     }
 
     this.inputEl = React.createRef();
     this.timeout = null;
     this.focusField = false;
   }
 
   componentDidMount() {
     const { data = [], storeName } = this.props;
     if(!data.length && storeName) {
       this.handleSearch(storeName);
     }
   }


   fetch = (value, callback) => {
     if (this.timeout) {
       clearTimeout(this.timeout);
       this.timeout = null;
     }
     const fake = async () => {
       let res;
       //如果有传入的请求接口
       const { queryData = undefined } = this.props;
       //参数去空格
       const newParms = customTrimFunc({
         storeName: value,
         size: 50,
         current: 1,
         industrialBeltFlag: INDUSTRIAL_BELT_FLAG,
         querySrc: 0
       })
       if(queryData) {
         res = await queryData(newParms);
       } else {
         res = await queryFactoryList(newParms);
       }
       if (res.success) {
         const {
           data: { records },
         } = res;
         callback(records);
       } else {
         callback([]);
       }
     }
     this.timeout = setTimeout(fake, 300);
   }
 
   //渲染历史搜索框
   renderStoreHistory = () => {
     const { storeArr } = this.state;
     if(storeArr.length > 0) {
       return (
         <div style={{ maxHeight: '160px', overflowY: 'auto' }}>
           <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px', fontSize: '12px' }}>
             <span className='common-color5'>最近搜索</span>
             <span className='common-color2' onClick={this.handleClearAllHistory}>清空</span>
           </div>
           {
             storeArr.map((v, index) => {
               return (
                 <div key={index} className={styles.wrap}>
                   <Tooltip title={v}>
                     <span className={styles.history} onClick={this.handleSelectStore.bind(this, v)}>{v}</span>
                   </Tooltip>
                   <span style={{ width: '16px', cursor: 'pointer', marginLeft: '4px' }} onClick={this.handleClearHistory.bind(this, v)}>
                     <CloseOutlined />
                   </span>
                 </div> 
               )
             })
           }
         </div>
       )
     } else {
       return (
         <div>请输入供应商名称</div>
       )
     }
   }
 
   //清空历史搜索记录
   handleClearAllHistory = () => {
     setStoreList([]);
     this.setState({ storeArr: [] });
   }
 
   //删除单个历史记录
   handleClearHistory = val => {
     const { storeArr } = this.state;
     const arr = [ ...storeArr ];
     pull(arr, val);
     setStoreList(arr);
     this.setState({ storeArr: arr });
   }
   
   //选择历史记录
   handleSelectStore = val => {
     this.focusField = true;
     this.setState({ inputVal: val, visible: 3 }, () => {
       this.handleSearch(val);
       this.inputEl?.current?.focus(); 
     })
   }
 
   //点击展开和关闭历史记录下拉框
   handleVisibleChange = (val) => {
     const { inputVal, visible } = this.state;
     if(val) {//点击展开
       if(inputVal) {
         if(visible != 3) {
           this.setState({ visible: 3 });
         }
       } else {
         this.setState({ visible: 2 });
       }
     } else {//点击关闭
       if(inputVal) {
         return;
       } else {
         let timer = setTimeout(() => {
           clearTimeout(timer);
           timer = null;
           if(!this.inputEl.current) {
             return;
           }
           if(this.inputEl.current.input == document.activeElement) {
             return;
           } else {
             this.setState({ visible: 1 });
           }
         }, 100);
       }
     }
   }
   
   //选择下拉店铺
   handleSelect = (val) => {
     const { data, storeId, storeArr } = this.state;
     const { index } = this.props;
     this.inputEl?.current?.focus();
     if(val == storeId) {//当前点击与原选择数据相同，直接关闭下拉框
       this.setState({ visible: 1 })
     } else {
       const obj = find(data, [ 'storeId', val ]);
       if(obj){
        const arr = slice(union([ obj.storeName, ...storeArr ]),0, 20);
        this.setState({ storeId: val, inputVal: obj.storeName, visible: 1, storeArr: arr }, () => {
          setStoreList(arr);
          this.props.onChange && this.props.onChange(val, index, obj);
        })
       }
     }
   }
   
   //搜索事件触发
   handleSearch = (val) => {
     if(val) {
       this.setState({ loading: true }, () => {
         this.fetch(val, data => {
          setTimeout(this.setState({ data, loading: false }));
         });
       })
     }
   }
   
   //点击输入框输入事件
   handleChange = (e) => {
     const val = e.target.value;
     if(val) {
      this.setState({ visible: 3, inputVal: val, storeId: undefined }, () => {
        this.handleSearch(val);
      });
     } else {
       this.setState({ visible: 2, data: [], inputVal: undefined, storeId: undefined });
     }
   }
   
   //输入框失焦事件
   handleBlur = () => {
     let timer = setTimeout(() => {
      if(this.focusField){
        this.focusField = false;
        return;
      }
       clearTimeout(timer);
       timer = null;
       const { inputVal, storeId, visible } = this.state;
       const { index } = this.props;
       if(inputVal) {
         if(!this.inputEl.current) {
           return;
         }
        if(visible == 3) {
          if(storeId) {
            this.setState({ visible: 1 });
          } else {
            this.setState({ visible: 1, inputVal: undefined, data: [], storeId: undefined }, () => {
              this.props.onChange && this.props.onChange(undefined, index, {});
            });
          }
        }
       } else {
         this.props.onChange && this.props.onChange(undefined, index, {});
       }
     }, 200);
   }
 
   render() {
 
     const { data, loading, visible, storeId, inputVal } = this.state;
     const { width = '160px' } = this.props;

     const options = data.map(d => (
       <Option value={d.storeId} key={d.storeId} label={d.storeName}>
         <Tooltip title={d.storeName} >
           {d.storeName}
         </Tooltip>
       </Option>
     ))
     return (
       <div style={{ position: 'relative' }}>
         <Select 
           style={{ width, position: 'absolute', outline: 'none' }} 
           open={ visible == 3 } 
           value={ storeId }
           onChange={this.handleSelect.bind(this)}
           notFoundContent={ loading ? '加载中...' : '暂无数据' }
         >
           {options}
         </Select>
         <Popover
           title={null} 
           content={this.renderStoreHistory} 
           trigger='click'
           overlayStyle={{ padding: 0, width: width, position: 'absolute' }} 
           placement="bottomLeft" 
           visible={visible == 2}
           overlayClassName="select-area-common"
           onVisibleChange={this.handleVisibleChange}
         >
           <Input onBlur={this.handleBlur} ref={this.inputEl} value={inputVal} onInput={this.handleChange} style={{ width: width }} placeholder={this.props.placeholder || '请输入供应商名称'} />
         </Popover>
       </div>
     )
   }
 }
 
 